package com.wyt.common.reflection.demo;

import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Description: 用以实现插件化思维，即定义接口，实现类扩展接口，使用时将所有扩展类放到一个map中，后续根据情况选择不用的实现类进行处理
 * @Description: 这个插件化开发是假的，只能是同一个工程里用，真正的插件化开发应该是插件与项目是两个工程。真正的插件化开发可以参考 SdkPluginUtils
 * @Author wangyongtao
 * @Date 2022/3/15 16:12
 **/
public class PluginUseDemo {

    public static void getMap() throws Exception{
        Map<String,ITest> functionHandlerMap = new HashMap<>();

        // 初始化工具类
        Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                        .forPackages("com.wyt.common.reflection.demo")
                        .addScanners(new SubTypesScanner()).addScanners(new FieldAnnotationsScanner()));

        Set<Class<? extends ITest>> subTypes = reflections.getSubTypesOf(ITest.class);

        Iterator<Class<? extends ITest>> iterator = subTypes.iterator();
        while (iterator.hasNext()){
            Class s = iterator.next();

            Resource annotation = (Resource)s.getAnnotation(Resource.class);

            System.out.println(annotation.name());

            functionHandlerMap.put(annotation.name(),(ITest)s.newInstance());
        }

        System.out.println("finish:"+functionHandlerMap.size());
    }

    public static void main(String[] args) throws Exception{
        getMap();
    }


}
